const express = require('express');
const static = require('express-static');
const bodyParser = require('body-parser');
const multer = require('multer');
const multerObj = multer({ dest: './static/upload' });
const mysql = require('mysql');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const consolidate = require('consolidate');
const expressRoute = require('express-route');
const fs = require('fs');
const path = require('path');
//日志中间件
var morgan = require('morgan');
const passport = require("passport");
var server = express();
server.listen(8888);

//1.获取请求数据
//get自带
//bodyParser能给req对象增加一个body属性，用来查看post过来的数据
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.use(multerObj.any());

//passport初始化
server.use(passport.initialize());
require("./libs/passport")(passport);

//日志中间件
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
//日志打印到命令行
server.use(morgan('short'));
//日志写入log文件
server.use(morgan('short', {stream: accessLogStream}));

//2.cookie、session循环加密
server.use(cookieParser());
(function () {
  var keys = [];
  for (var i = 0; i < 100000; i++) {
    keys[i] = 'a_' + Math.random();
  }
  server.use(cookieSession({
    name: 'sess_id',
    keys: keys,
    maxAge: 20 * 60 * 1000 * 72  //20min乘72 一天
  }));
})();


//3.模板
server.engine('html', consolidate.ejs);
server.set('views', 'template');
server.set('view engine', 'html');

server.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  
  if (req.method == 'OPTIONS') {
    //让options请求快速返回
    res.sendStatus(200);
    return;
  } else {
    next();
  }
});

//4.前台数据返回
server.use('/', require('./route/web/index.js')());
//后台接口数据
server.use('/admin/', require('./route/admin/userlogin.js')());
server.use('/admin/', require('./route/admin/data.js')());

//5.default：static
server.use(static('./static/'));